package com.beyondsoft.common.core.exchange.receiver;

import com.beyondsoft.common.core.constant.TransactionConstants;
import com.beyondsoft.common.core.exchange.model.Message;
import com.beyondsoft.common.core.exchange.sender.MainToSubSender;
import com.beyondsoft.common.core.redis.RedisMsService;
import com.beyondsoft.common.core.sys.initialization.RabbitConfig;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 收集远程服务执行情况
 */
@Component
@RabbitListener(queues = RabbitConfig.STATE_QUEUE)
public class MainReceiver {

    @Autowired
    private RedisMsService redisMsService;
    @Autowired
    private MainToSubSender mainToSubSender;

    /**
     * 主线程查询所有子服务状态
     *
     * @param keys
     * @return
     */
    private int checkManage(Set<String> keys) {
        int manage = TransactionConstants.PACKAGEKEY_STATUS_INIT;
        for (String key : keys) {
            int keyManage = TransactionConstants.PACKAGEKEY_STATUS_INIT;
            if (redisMsService.get(key) != null) {
                keyManage = (int) redisMsService.get(key);
            }
            if (keyManage == TransactionConstants.PACKAGEKEY_STATUS_ERROE) {
                return TransactionConstants.PACKAGEKEY_STATUS_ERROE;
            }
            manage += keyManage;
        }
        if (manage == keys.size() * TransactionConstants.PACKAGEKEY_STATUS_SUCCESS) {
            return TransactionConstants.PACKAGEKEY_STATUS_SUCCESS;
        }
        return TransactionConstants.PACKAGEKEY_STATUS_INIT;
    }

    @RabbitHandler
    public void process(String packageKey) {
        System.out.println("收到服务执行成功通知");
        //等待子线程全部处理完毕
        Set<String> keys = redisMsService.getKeyList(packageKey + ":*");
        //主线程控制提交
        keys.add(packageKey);
        //执行结果，默认为0 正在执行
        Integer manage;
        //存在remote
        if (keys.size() > 0) {
            manage = checkManage(keys);
        }
        //没有remote
        else {
            manage = checkManage(new HashSet<>(Arrays.asList(packageKey)));
            //失败状态回滚
            if (manage != TransactionConstants.PACKAGEKEY_STATUS_ERROE) {
                //未失败自动成功
                manage = TransactionConstants.PACKAGEKEY_STATUS_SUCCESS;
            }
        }
        //有结果了，发送通知
        if (manage != TransactionConstants.PACKAGEKEY_STATUS_INIT) {

            System.out.println("获取到执行结果-开始发送处理通知");
            mainToSubSender.send(new Message(packageKey, manage));
        }

    }

}
